import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Input } from 'antd';

import styles from './style.scss';

export default class TextArea extends Component {
    static propTypes = {
        showContentSize: PropTypes.bool,
    };

    static defaultProps = {
        showContentSize: false
    };

    constructor(props) {
        super(props);
        this.state = {
            contentSize: props.value && props.value.length || 0
        };
    }

    componentWillReceiveProps(nextProps) {
        if (nextProps.value !== this.props.value) {
            this.setState({
                contentSize: nextProps.value && nextProps.value.length || 0
            });
        }
    }

    onInput = evt => {
        const { showContentSize, onInput } = this.props;
        if (showContentSize) {
            this.setState({
                contentSize: evt.target.value.length
            });
        }
        onInput && onInput(evt);
    };

    render() {
        const { showContentSize, onInput, style, ...props } = this.props;
        let contentSizeText = '';
        if (showContentSize) {
            contentSizeText = this.state.contentSize;
            if (this.props.maxLength) {
                contentSizeText += '/' + this.props.maxLength;
            }
        }
        return (
            <div className={styles.textarea} style={style}>
                <div className={styles.textareaContainer}>
                    <Input.TextArea
                        onInput={this.onInput}
                        {...props}
                    />
                    {
                        contentSizeText && <span className={styles.contentSize}>{contentSizeText}</span>
                    }
                </div>
            </div>
        );
    }
}
